/**
 *1. 条件函数作为参数，根据需求返回需要组合的key
  2. 为了适配多种传参，将参数统一处理为函数（参数归一化思想）
 * @param {*} arr
 * @param {*} proKeyFn
 */
function arrayCombination(arr, proKeyFn) {
  let result = {};

  // 参数归一化成函数
  if (typeof proKeyFn === "string") {
    proKeyFn = (item) => item[proKeyFn];
  }

  arr.forEach((item) => {
    // 提供函数，根据函数返回值作为key
    let key = proKeyFn(item);

    if (result[key]) {
      result[key].push(item);
    } else {
      result[key] = [item];
    }
  });

  return result;
}

let arr = [
  { age: 1, name: "li" },
  { age: 2, name: "zhang" },
  { age: 3, name: "wu" },
  { age: 4, name: "hao" },
  { age: 4, name: "xu" },
  { age: 2, name: "lin" },
  { age: 6, name: "lin" },
];

console.log(arrayCombination(arr, "age"));

console.log(
  arrayCombination(arr, (item) => {
    return item.age;
  })
);

console.log(
  arrayCombination(arr, (item) => {
    return item.name;
  })
);

// key还可以自行多加其他字符串
console.log(
  arrayCombination(arr, (item) => {
    return item.age + "age";
  })
);
